package com.yuji.aacar.controller.cartype;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.yuji.aacar.R;
import com.yuji.aacar.base.BaseActivity;
import com.yuji.aacar.base.EventConst;
import com.yuji.aacar.base.UserCenter;
import com.yuji.aacar.bean.beans.Brand;
import com.yuji.aacar.bean.beans.Serial;
import com.yuji.aacar.bean.request.ManagePersonalCarRequest;
import com.yuji.aacar.bean.response.GetAllBrandResponse;
import com.yuji.aacar.bean.response.GetDataVersionResponse;
import com.yuji.aacar.bean.response.GetSeriesListResponse;
import com.yuji.aacar.bean.response.HotBrandResponse;
import com.yuji.aacar.bean.response.LoginResponse;
import com.yuji.aacar.bean.response.ManagePersonalCarResponse;
import com.yuji.aacar.controller.adapter.CarSerialAdapter;
import com.yuji.aacar.controller.adapter.ChooseCarAdapter;
import com.yuji.aacar.controller.adapter.RecyclerViewItemTouchListener;
import com.yuji.aacar.controller.cartype.bean.CarBean;
import com.yuji.aacar.core.cores.event.CoreEventBusMessage;
import com.yuji.aacar.core.cores.event.CoreEventCenter;
import com.yuji.aacar.core.cores.fres.CoreImageLoader;
import com.yuji.aacar.core.cores.services.CoreServiceResponse;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.service.BaseServiceMediator;
import com.yuji.aacar.service.BaseServiceParams;
import com.yuji.aacar.widgets.autolayout.AutoFrameLayout;
import com.yuji.aacar.widgets.autolayout.AutoRelativeLayout;
import com.yuji.aacar.widgets.edittext.ChooseCancelEditText;
import com.yuji.aacar.widgets.indexview.suspension.SuspensionDecoration;
import com.yuji.aacar.widgets.indexview.widget.IndexBar;
import com.yuji.aacar.widgets.swiplistview.WSwipeMenuListView;
import com.yuji.aacar.widgets.textview.PingFangTextView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import static com.yuji.aacar.service.BaseServiceMediator.GET_SERIES_LIST;
import static com.yuji.aacar.service.BaseServiceMediator.GET_SERIES_LIST_BYNAME;
import static com.yuji.aacar.service.BaseServiceMediator.MANAGE_PERSONAL_CAR;

/**
 * <li>Package:com.yuji.aacar.controller.cartype</li>
 * <li>Author: lining </li>
 * <li>Date: 2018/3/8</li>
 * <li>Description:   </li>
 */

public class ChooseCarTypeActivity extends BaseActivity {

    ChooseCarTypeActivityVM chooseCarTypeActivityVM;
    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.back_image)
    AutoRelativeLayout backImage;
    @BindView(R.id.title_content)
    PingFangTextView titleContent;
    @BindView(R.id.back_login)
    PingFangTextView backLogin;
    @BindView(R.id.title_message_iv)
    ImageView titleMessageIv;
    @BindView(R.id.title_message_rl)
    AutoRelativeLayout titleMessageRl;
    @BindView(R.id.title_rl)
    AutoRelativeLayout titleRl;
    @BindView(R.id.choose_car_iv)
    ImageView chooseCarIv;
    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.tvSideBarHint)
    TextView tvSideBarHint;
    @BindView(R.id.indexBar)
    IndexBar indexBar;
    @BindView(R.id.choose_car_slide_rv)
    WSwipeMenuListView chooseCarSlideRv;
    @BindView(R.id.main_right_drawer_layout)
    AutoRelativeLayout mainRightDrawerLayout;
    @BindView(R.id.main_drawer_layout)
    DrawerLayout mainDrawerLayout;
    @BindView(R.id.choose_car_slide_iv)
    SimpleDraweeView chooseCarSlideIv;
    @BindView(R.id.choose_car_slide_tv)
    PingFangTextView chooseCarSlideTv;
    @BindView(R.id.choose_car_edit)
    ChooseCancelEditText chooseCarEdit;
    @BindView(R.id.choose_car_middle_layout)
    AutoFrameLayout chooseCarMiddleLayout;
    @BindView(R.id.search_view)
    WSwipeMenuListView searchView;


    private ChooseCarAdapter mAdapter;
    private ViewHolder mHolder;
    private HeaderRecyclerAndFooterWrapperAdapter mHeaderAdapter;
    private LinearLayoutManager mManager;
    private List<CarBean> mDatas;
    private SuspensionDecoration mDecoration;
    private ArrayList<Brand> hotBrands;
    private ArrayList<SimpleDraweeView> fresoView;
    private ArrayList<PingFangTextView> textList;
    private ArrayList<Brand> allBrands;

    private ArrayList<Serial> list = new ArrayList<>();
    private ArrayList<Serial> searchList = new ArrayList<>();
    private CarSerialAdapter adapter;
    private CarSerialAdapter searchAdapter;


    // 抽屉菜单对象
    private ActionBarDrawerToggle drawerbar;
    public DrawerLayout drawerLayout;

    /**
     * 右侧边栏导航区域
     */
    private IndexBar mIndexBar;

    /**
     * 显示指示器DialogText
     */
    private TextView mTvSideBarHint;

    private Serial selectedSerial;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        //取消顶部标题
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //设置全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_choose_car_type);
        ButterKnife.bind(this);
        initTitle(true, "选择车型", null);
        super.onCreate(savedInstanceState);

//        isFirst = getIntent().getIntExtra("isfirst", 0);

        initBrandList();
        initSlideList();
        initSearchView();
    }

    private void initSearchView() {
        searchAdapter = new CarSerialAdapter(ChooseCarTypeActivity.this, searchList);
        searchView.setAdapter(searchAdapter);
        searchView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != searchList && searchList.size() > 0){
                    searchList.get(position);
                    selectedSerial = searchList.get(position);
                    requestAddUserCar(selectedSerial);
                }
            }
        });
    }

    @Override
    public void alreadyBindBaseViewModel() {
        super.alreadyBindBaseViewModel();
        requestBrandVersion();
    }

    private void initSlideList() {
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int windowsWight = metric.widthPixels;
        int windowsHeight = metric.heightPixels;


        drawerLayout = (DrawerLayout) findViewById(R.id.main_drawer_layout);
        ViewGroup.LayoutParams leftParams = drawerLayout.getLayoutParams();
        leftParams.height = windowsHeight;
        leftParams.width = windowsWight;
        drawerLayout.setLayoutParams(leftParams);


        //设置菜单内容之外其他区域的背景色
        drawerLayout.setScrimColor(Color.TRANSPARENT);
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        //右边菜单
        AutoRelativeLayout main_right_drawer_layout = (AutoRelativeLayout) findViewById(R.id.main_right_drawer_layout);

        drawerbar = new ActionBarDrawerToggle(this, drawerLayout, null, R.string.open, R.string.close) {
            //菜单打开
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                chooseCarEdit.setEnabled(false);
            }

            // 菜单关闭
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                chooseCarEdit.setEnabled(true);
            }
        };

        drawerLayout.setDrawerListener(drawerbar);

        adapter = new CarSerialAdapter(ChooseCarTypeActivity.this, list);
        chooseCarSlideRv.setAdapter(adapter);
        chooseCarSlideRv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (null != list && list.size() > 0){
                    selectedSerial = list.get(position);
                    requestAddUserCar(selectedSerial);
                }
            }
        });

        chooseCarEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String str = s.toString().toString();
                if (!TextUtils.isEmpty(str)) {
                    chooseCarMiddleLayout.setVisibility(View.GONE);
                    searchView.setVisibility(View.VISIBLE);

                    if (!TextUtils.isEmpty(s.toString())){
                        requestCarSerialByName(s.toString());
                    }
                } else {
                    searchView.setVisibility(View.GONE);
                    chooseCarMiddleLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        chooseCarEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEND || (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    String brandName = v.getText().toString().trim();
                    if (!TextUtils.isEmpty(brandName)){
                        requestCarSerialByName(brandName);
                        return true;
                    }
                }
                return false;
            }
        });
    }

    private void initBrandList() {

        mRv.setLayoutManager(mManager = new LinearLayoutManager(this));

        mAdapter = new ChooseCarAdapter(this, mDatas);
        mHeaderAdapter = new HeaderRecyclerAndFooterWrapperAdapter(mAdapter) {
            @Override
            protected void onBindHeaderHolder(ViewHolder holder, int headerPos, int layoutId, Object o) {
                //                holder.setText(R.id.choose_car_item_carname, (String) o);
                mHolder = holder;
                fresoView = new ArrayList<>();
                fresoView.add(holder.getView(R.id.choose_car_brand_one_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_two_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_three_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_four_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_five_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_six_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_seven_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_eight_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_nine_iv));
                fresoView.add(holder.getView(R.id.choose_car_brand_ten_iv));

                textList = new ArrayList<>();
                textList.add(holder.getView(R.id.choose_car_brand_one_name));
                textList.add(holder.getView(R.id.choose_car_brand_two_name));
                textList.add(holder.getView(R.id.choose_car_brand_three_name));
                textList.add(holder.getView(R.id.choose_car_brand_four_name));
                textList.add(holder.getView(R.id.choose_car_brand_five_name));
                textList.add(holder.getView(R.id.choose_car_brand_six_name));
                textList.add(holder.getView(R.id.choose_car_brand_seven_name));
                textList.add(holder.getView(R.id.choose_car_brand_eight_name));
                textList.add(holder.getView(R.id.choose_car_brand_nine_name));
                textList.add(holder.getView(R.id.choose_car_brand_ten_name));
            }
        };
        mHeaderAdapter.setHeaderView(R.layout.activity_choose_car_header, "品牌");

        mRv.setAdapter(mHeaderAdapter);
        mRv.addItemDecoration(mDecoration = new SuspensionDecoration(this, mDatas).setHeaderViewCount(mHeaderAdapter.getHeaderViewCount()));

        //如果add两个，那么按照先后顺序，依次渲染。
        mRv.addItemDecoration(new DividerItemDecoration(ChooseCarTypeActivity.this, DividerItemDecoration.VERTICAL_LIST));

        //使用indexBar
        mTvSideBarHint = (TextView) findViewById(R.id.tvSideBarHint);//HintTextView
        mIndexBar = (IndexBar) findViewById(R.id.indexBar);//IndexBar

        mIndexBar.setmPressedShowTextView(mTvSideBarHint)//设置HintTextView
                .setNeedRealIndex(true)//设置需要真实的索引
                .setmLayoutManager(mManager);//设置RecyclerView的LayoutManager

        mRv.addOnItemTouchListener(new RecyclerViewItemTouchListener(mRv, new RecyclerViewItemTouchListener.OnItemClickListener() {

            @Override
            public void onItemClick(View view) {
                LogUtil.e("--onItemClick--", mRv.getChildViewHolder(view).getPosition());
                if (mRv.getChildViewHolder(view).getPosition() == 0) {

                } else {
                    ChooseCarAdapter.ViewHolder holder = (ChooseCarAdapter.ViewHolder) mRv.getChildViewHolder(view);
                    LogUtil.e("选择的品牌是--holder--", holder);
                    requestCarSerial(holder.getBrandId());
                    CoreImageLoader.loadImage(chooseCarSlideIv, holder.getBrandUrl());
                    chooseCarSlideTv.setText(holder.getCarName().getText().toString());
                }
            }

            @Override
            public void onItemLongClick(View view) {

            }
        }));
    }


    private void requestHotBrand() {
        requestParams = BaseServiceParams.getHotBrand();
        doTask(BaseServiceMediator.GET_HOT_BRAND);
    }

    private void requestAllBrand() {
        requestParams = BaseServiceParams.getAllBrand("0", "200");
        doTask(BaseServiceMediator.GET_ALL_BRAND);
    }

    private void requestBrandVersion() {
        requestParams = BaseServiceParams.getDataVersion("t_car_series");
        doTask(BaseServiceMediator.GET_DATA_VERSION);
    }

    private void requestCarSerial(String brandId) {
        requestParams = BaseServiceParams.getSeriesList(brandId);
        doTask(GET_SERIES_LIST);
    }

    private void requestCarSerialByName(String brandName) {
        requestParams = BaseServiceParams.getSeriesByName(brandName);
        doTask(GET_SERIES_LIST_BYNAME);
    }

    private void requestAddUserCar(Serial serial) {
        ManagePersonalCarRequest request = new ManagePersonalCarRequest();
        request.setOperatorFlag("1");
        request.setCarType(serial.getCarType());
        request.setBrandId(serial.getBrandId());
//        request.setBrandName(serial.getBrandName());
//        request.setBrandUrl(serial.getBrandUrl());
        request.setCarLibType(serial.getCarLibType());
        request.setSeriesName(serial.getSeriesName());
        request.setSeriesType(serial.getSeriesType());
//        selectedSerial = serial;
        requestParams = BaseServiceParams.managePersonalCar(request);
        doTask(MANAGE_PERSONAL_CAR);
    }

    @Override
    public void requestSuccess(CoreServiceResponse response) {
        super.requestSuccess(response);
        if (response.getRequestCode() == BaseServiceMediator.GET_HOT_BRAND_CODE) {
            HotBrandResponse hotBrandResponse = (HotBrandResponse) response.getResponse();
            hotBrands = hotBrandResponse.getInfo();
            requestAllBrand();
            resetHeaderDate();
        } else if (response.getRequestCode() == BaseServiceMediator.GET_ALL_BRAND_CODE) {
            GetAllBrandResponse allBrandResponse = (GetAllBrandResponse) response.getResponse();
            allBrands = allBrandResponse.getInfo();
            showToast(allBrands.size() + "");
            resetBrandList();
        } else if (response.getRequestCode() == BaseServiceMediator.GET_DATA_VERSION_CODE) {
            GetDataVersionResponse dataVersionResponse = (GetDataVersionResponse) response.getResponse();
            showToast(dataVersionResponse.getVersion());
            requestHotBrand();
        } else if (response.getRequestCode() == BaseServiceMediator.GET_SERIES_LIST_CODE) {
            GetSeriesListResponse seriesListResponse = (GetSeriesListResponse) response.getResponse();
            resetSliderDate(seriesListResponse);
        } else if ( response.getRequestCode() == BaseServiceMediator.GET_SERIES_LIST_BYNAME_CODE) {
            GetSeriesListResponse seriesListResponse = (GetSeriesListResponse) response.getResponse();
            resetSearchDate(seriesListResponse);
        } else if ( response.getRequestCode() == BaseServiceMediator.MANAGER_PERSONAL_CAR_NEW) {
            ManagePersonalCarResponse personalCarResponse = (ManagePersonalCarResponse) response.getResponse();
            if (personalCarResponse.isSuccess()){

                LoginResponse user = UserCenter.getCurrentUser();
                if (null != user){
                    if (UserCenter.isFirstUse(user.getMemberId())){
                        UserCenter.setFirstCar(user.getMemberId(),selectedSerial);
                        CoreEventCenter.postObject(EventConst.FIRST_DEFAULT_SERIAL_FINISH, selectedSerial);
                    }
                }
                this.finish();
            }
        }
    }

    private void resetHeaderDate() {
        if (null != hotBrands && hotBrands.size() > 0) {
            for (int i = 0; i < hotBrands.size(); i++) {
                Brand brand = hotBrands.get(i);
                CoreImageLoader.loadImage(fresoView.get(i), brand.getBrandUrl());
                textList.get(i).setText(brand.getBrandName());

                fresoView.get(i).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.e("选择的品牌是--", brand);
                        CoreImageLoader.loadImage(chooseCarSlideIv, brand.getBrandUrl());
                        chooseCarSlideTv.setText(brand.getBrandName());
                        requestCarSerial(brand.getBrandId());
                    }
                });
                textList.get(i).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LogUtil.e("选择的品牌是--", brand);
                        CoreImageLoader.loadImage(chooseCarSlideIv, brand.getBrandUrl());
                        chooseCarSlideTv.setText(brand.getBrandName());
                        requestCarSerial(brand.getBrandId());
                    }
                });
            }
        }
        //        mHeaderAdapter.notifyDataSetChanged();
    }

    private void resetBrandList() {
        if (null != allBrands && allBrands.size() > 0) {

            getWindow().getDecorView().postDelayed(new Runnable() {
                @Override
                public void run() {

                    if (null != allBrands && allBrands.size() > 0) {
                        mDatas = new ArrayList<CarBean>();
                        for (int i = 0; i < allBrands.size(); i++) {
                            Brand brand = allBrands.get(i);
                            CarBean car = new CarBean(brand.getBrandName() == null ? "#" : brand.getBrandName());
                            car.setCarUrl(brand.getBrandUrl());
                            car.setBrandId(brand.getBrandId());
                            mDatas.add(car);
                        }
                        mIndexBar.setmSourceDatas(mDatas)//设置数据
                                .setHeaderViewCount(mHeaderAdapter.getHeaderViewCount())//设置HeaderView数量
                                .invalidate();

                        mAdapter.setDatas(mDatas);
                        mHeaderAdapter.notifyDataSetChanged();
                        mDecoration.setmDatas(mDatas);

                        LogUtil.e("resetBrandList", mDatas.size());
                    }

                }
            }, 200);

        }
    }

    private void resetSliderDate(GetSeriesListResponse seriesListResponse) {
        ArrayList<Serial> serials = seriesListResponse.getInfo();
        list.clear();
        if (null != serials && serials.size() > 0) {
            for (int i = 0; i < serials.size(); i++) {
                list.add(serials.get(i));
            }
        }
        adapter.notifyDataSetChanged();
        drawerLayout.openDrawer(GravityCompat.END);
    }

    private void resetSearchDate(GetSeriesListResponse seriesListResponse) {
        ArrayList<Serial> serials = seriesListResponse.getInfo();
        searchList.clear();
        if (null != serials && serials.size() > 0) {
            for (int i = 0; i < serials.size(); i++) {
                searchList.add(serials.get(i));
            }
        }
        searchAdapter = new CarSerialAdapter(ChooseCarTypeActivity.this, searchList);
        searchAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.closeDrawer(Gravity.RIGHT);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
            drawerLayout.closeDrawer(Gravity.RIGHT);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void handleMessage(CoreEventBusMessage message) {
        super.handleMessage(message);
        if (message.getMessageCode().contentEquals(String.valueOf(EventConst.FIRST_SELECT_OVER))) {
            this.finish();
        }
    }
}
